"""
API Key管理接口
用于查看API Key使用统计和管理第三方访问
"""
from fastapi import APIRouter, HTTPException, Depends, Request
from typing import Dict, Any

from server.utils.api_key_utils import api_key_tracker, APIKeyConfig
from server.utils.auth_middleware import get_admin_user, get_superadmin_user
from server.models.user_model import User
from src.utils.logging_config import logger

api_key_router = APIRouter(prefix="/api-key", tags=["api-key"])


@api_key_router.get("/stats")
async def get_api_key_stats(current_user: User = Depends(get_admin_user)) -> Dict[str, Any]:
    """
    获取API Key使用统计（管理员权限）

    Returns:
        API Key使用统计信息
    """
    try:
        base_stats = api_key_tracker.get_stats()

        # 构建完整的统计信息
        stats = {
            "status": "success",
            "data": {
                "enabled": APIKeyConfig.API_KEY_ENABLED,
                "current_key_status": "configured" if APIKeyConfig.THIRD_PARTY_API_KEY else "not_configured",
                "current_hour_usage": base_stats["current_hour_usage"],
                "hourly_limit": base_stats["hourly_limit"],
                "usage_percentage": round((base_stats["current_hour_usage"] / base_stats["hourly_limit"]) * 100, 2) if base_stats["hourly_limit"] > 0 else 0,
                "allowed_paths": APIKeyConfig.API_KEY_ALLOWED_PATHS,
                "allowed_ips": APIKeyConfig.API_KEY_ALLOWED_IPS,
                "recent_logs": base_stats["recent_logs"][:50]  # 只返回最近50条记录
            }
        }

        return stats

    except Exception as e:
        logger.error(f"获取API Key统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@api_key_router.get("/config")
async def get_api_key_config(current_user: User = Depends(get_admin_user)) -> Dict[str, Any]:
    """
    获取API Key配置信息（管理员权限）

    Returns:
        当前API Key配置（脱敏显示）
    """
    try:
        # 脱敏显示API Key（只显示前后几位）
        api_key_display = "未配置"
        if APIKeyConfig.THIRD_PARTY_API_KEY:
            key = APIKeyConfig.THIRD_PARTY_API_KEY
            if len(key) > 8:
                api_key_display = f"{key[:4]}...{key[-4:]}"
            else:
                api_key_display = "***"

        config_info = {
            "status": "success",
            "data": {
                "enabled": APIKeyConfig.API_KEY_ENABLED,
                "api_key": api_key_display,
                "rate_limit": APIKeyConfig.API_KEY_RATE_LIMIT,
                "allowed_ips": APIKeyConfig.API_KEY_ALLOWED_IPS,
                "allowed_paths_count": len(APIKeyConfig.API_KEY_ALLOWED_PATHS),
                "allowed_paths": APIKeyConfig.API_KEY_ALLOWED_PATHS
            },
            "message": "注意：真实的API Key仅在环境变量中存储，不会在此处完全显示"
        }

        return config_info

    except Exception as e:
        logger.error(f"获取API Key配置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@api_key_router.post("/test")
async def test_api_key_access(
    request: Request,
    test_path: str = "/api/system/health",
    current_user: User = Depends(get_admin_user)
) -> Dict[str, Any]:
    """
    测试API Key访问（管理员权限）

    Args:
        test_path: 要测试的接口路径
        current_user: 当前用户

    Returns:
        测试结果
    """
    try:
        # 检查路径是否允许API Key访问
        is_allowed = APIKeyConfig.is_path_allowed_for_api_key(test_path)

        # 获取当前用户的IP地址
        client_ip = request.client.host
        is_ip_allowed = APIKeyConfig.is_ip_allowed(client_ip)

        result = {
            "status": "success",
            "data": {
                "test_path": test_path,
                "is_path_allowed": is_allowed,
                "is_ip_allowed": is_ip_allowed,
                "can_access": is_allowed and is_ip_allowed and APIKeyConfig.API_KEY_ENABLED,
                "api_key_configured": bool(APIKeyConfig.THIRD_PARTY_API_KEY),
                "api_key_enabled": APIKeyConfig.API_KEY_ENABLED,
                "client_ip": client_ip
            }
        }

        if not is_allowed:
            result["message"] = "该接口不支持API Key访问"
        elif not is_ip_allowed:
            result["message"] = "当前IP地址不在白名单中"
        elif not APIKeyConfig.API_KEY_ENABLED:
            result["message"] = "API Key功能未启用"
        elif not APIKeyConfig.THIRD_PARTY_API_KEY:
            result["message"] = "API Key未配置"
        else:
            result["message"] = "配置正常，可以访问"

        return result

    except Exception as e:
        logger.error(f"API Key访问测试失败: {e}")
        raise HTTPException(status_code=500, detail=f"测试失败: {str(e)}")


@api_key_router.get("/logs")
async def get_api_key_logs(
    limit: int = 100,
    current_user: User = Depends(get_admin_user)
) -> Dict[str, Any]:
    """
    获取API Key调用日志（管理员权限）

    Args:
        limit: 返回日志条数限制
        current_user: 当前用户

    Returns:
        API Key调用日志
    """
    try:
        stats = api_key_tracker.get_stats()
        logs = stats["recent_logs"][:limit]

        result = {
            "status": "success",
            "data": {
                "logs": logs,
                "total_count": len(logs),
                "hourly_usage": stats["current_hour_usage"],
                "hourly_limit": stats["hourly_limit"]
            }
        }

        return result

    except Exception as e:
        logger.error(f"获取API Key调用日志失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取日志失败: {str(e)}")


@api_key_router.post("/refresh")
async def refresh_api_key_usage(current_user: User = Depends(get_superadmin_user)) -> Dict[str, Any]:
    """
    刷新API Key使用统计（超级管理员权限）
    清空当前小时的使用计数

    Returns:
        操作结果
    """
    try:
        # 重置当前小时的使用计数
        from server.utils.api_key_utils import APIKeyUsageTracker
        new_tracker = APIKeyUsageTracker()
        globals()['api_key_tracker'] = new_tracker

        logger.info(f"超级管理员 {current_user.username} 刷新了API Key使用统计")

        return {
            "status": "success",
            "message": "API Key使用统计已重置",
            "data": {
                "refreshed_by": current_user.username,
                "refreshed_at": datetime.now().isoformat()
            }
        }

    except Exception as e:
        logger.error(f"刷新API Key使用统计失败: {e}")
        raise HTTPException(status_code=500, detail=f"刷新失败: {str(e)}")


from datetime import datetime